<!--
 * @Descripttion: 新增进货单
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-12 15:10:47
 -->
<template>
  <div class="bill_container">
    <affix>
      <div class="clearfix paddingLR20">
        <div class="oper-button btn-group fl">
          <SelectGoodsBtns
            :price-cat-name="defaultPriceCatName"
            :price-cat="defaultPriceCat"
            :show-tab-names="['all','maxstock']"
            @on-select-sure="onSelectGoodsSure"
          />
        </div>
        <div class="oper-button btn-group fr">
          <el-button type="default" @click="btnJump2List">历史单据</el-button>
          <el-button type="primary" :loading="btnLoading.save" @click="btnSave">保存(Ctrl+S)</el-button>
          <el-button type="default" :loading="btnLoading.save" @click="btnSave({readd:true})">保存并新增(F9)</el-button>
        </div>
      </div>
    </affix>
    <el-main>
      <el-form
        ref="billForm"
        :model="dataObj"
        :rules="ruleValidator"
        label-position="left"
        inline
        label-width="80px"
      >
        <el-card shadow="never">
          <div slot="header" class="header clearfix">
            <div class="clearfix index_container form">
              <div class="fl">
                <el-form-item
                  label="供应商"
                  label-width="70px"
                  prop="comegoId"
                >
                  <SelectComego
                    ref="comego"
                    v-model="dataObj.comegoId"
                    class="w150"
                    :default-value="dataObj.comegoName"
                    comego-name="SupplierList"
                    @change="onComegoChange"
                  />
                </el-form-item>
              </div>
              <div class="fr">
                <el-form-item class="bill-number white-border" label="单据编号: " prop="billNo">
                  <el-input v-model="dataObj.billNo" class="w150" size="mini" />
                </el-form-item>
              </div>
            </div>
            <div class="index_container title">
              <h1> 进货退货单 </h1>
            </div>
          </div>
          <div class="clearfix">
            <div class="fl">
              <el-checkbox v-model="dataObj.isPrint" label="保存后打印" border />
            </div>
            <div class="fr">
              <el-form-item label="经手人:" prop="handUserId">
                <SelectEmployee
                  v-model="dataObj.handUserId"
                  :is-set-default="true"
                />
              </el-form-item>
              <el-form-item label="业务日期:">
                <el-date-picker v-model="dataObj.businessTime" class="w150" type="datetime" />
              </el-form-item>
            </div>
          </div>
          <goods-select
            ref="GoodsSelect"
            :is-open-tax="isOpenTax"
            :tax-rate="taxRate"
            :price-cat="[defaultPriceCat]"
            :default-price-cat="defaultPriceCat"
          />
          <div class="bottom">
            <table class="table" border="1" cellspacing="0" cellpadding="0">
              <tr>
                <td align="right" @mouseenter="onTdMouseEnter" @mouseleave="onTdMouseLeave">
                  <div class="w300">
                    <el-form-item label="其他费用:" class="white-border">
                      <el-input v-model="dataObj.amountOther" class="text-right" />
                    </el-form-item>
                  </div>
                </td>
                <td :width="tableFixedWidth" class="bg-blue">
                  <el-form-item
                    label="结算账户:"
                    label-width="90px"
                    prop="accountId"
                    style="width:100%"
                  >
                    <SelectAccount
                      v-model="dataObj.accountId"
                    />
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td align="right">
                  <div class="w200">
                    <el-form-item label="应付金额:" prop="amountPayable">
                      {{ dataObj.amountPayable }}
                    </el-form-item>
                  </div>
                </td>
                <td :width="tableFixedWidth" class="bg-blue">
                  <el-form-item label="实付金额:" prop="amountPaid">
                    <el-input v-model.number="dataObj.amountPaid" />
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td style="padding:0;" @mouseenter="onTdMouseEnter" @mouseleave="onTdMouseLeave">
                  <table class="wfull" border="0" cellspacing="0" cellpadding="0">
                    <tr class="lastrow">
                      <td width="100">
                        备 注:
                      </td>
                      <td class="lastCol">
                        <el-input v-model="dataObj.remarks" class="wfull" type="textarea" />
                      </td>
                    </tr>
                  </table>
                </td>
                <td :width="tableFixedWidth" style="padding:0; position: relative; overflow: hidden;">
                  <el-button class="full-button" type="primary" :loading="btnLoading.save" @click="btnSave">保存(Ctrl+S)</el-button>
                </td>
              </tr>
            </table>
          </div>
        </el-card>
      </el-form>
    </el-main>
  </div>
</template>

<script>
import { oftenuse } from '@/libs/mixins'
import { addData as addReturnPurchase } from '@/api/bill/bill-purchase-return.js'
import { amount } from '@/libs/tools.js'
import { add, update } from './mixins'
import { priceCat, price } from '@/views/bill/purchase/mixins'
import GoodsSelect from '@/views/goods-select'
import Affix from '@/components/Affix'
import moment from 'moment'
import clonedeep from 'clonedeep'
import SelectComego from '@/views/components/SelectComego'
import SelectAccount from '@/views/components/SelectAccount'
import SelectEmployee from '@/views/components/SelectEmployee'
import SelectGoodsBtns from '@/views/components/SelectGoodsBtns'

export default {
  name: 'PurchasereturnAddNoRelation',
  components: { GoodsSelect, SelectGoodsBtns, SelectEmployee, SelectAccount, SelectComego, Affix },
  filters: {
    goodAmount: function(row) {
      return amount(row.price).multiply(row.num).format()
    }
  },
  mixins: [add, update, oftenuse, priceCat, price],
  props: {
    billId: {
      type: String,
      default: null
    },
    operation: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      ruleValidator: {
        comegoId: [
          { required: true, message: '请选择供应商', trigger: 'blur' }
        ],
        accountId: [
          { required: true, message: '请选择计算账户', trigger: 'change' }
        ],
        amountPaid: [
          { validator: (rule, value, callback) => {
            const amountPayable = this.dataObj.amountPayable
            if (value > amountPayable) return callback(new Error(`金额不能大于${amountPayable}`))
            callback()
          } }
        ]
      },
      tableFixedWidth: 300,
      goodsSelectComp: null
    }
  },
  computed: {
  },
  watch: {
  },
  mounted() {
    this.goodsSelectComp = this.$refs.GoodsSelect
  },
  created() {
    this.initData()
  },
  methods: {
    btnJump2List() {
      this.jump2List()
    },
    btnSave({ readd }) {
      this.handleVali().then(_ => {
        const billDetailList = clonedeep(this.$refs.GoodsSelect.getPostData())
        const bill = clonedeep(this.dataObj)
        if (billDetailList.length === 0) return this.$message.error('请选择商品！')
        const params = { bill, billDetailList }
        this.setBtnLoading('save', true)
        this.saveData(params).then((res) => {
          this.setBtnLoading('save', false)
          if (!res.data.flag) return
          if (readd) {
            this.resetData()
          } else {
            this.jump2List()
          }
        }).catch(err => {
          console.log(err)
          this.setBtnLoading('save', false)
        })
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // api
    jump2List() {
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'PurchasereturnList',
        params: { refresh: true }
      })
    },
    handleVali() {
      const v1 = this.handleValid('billForm')
      const v2 = this.$refs.GoodsSelect.valiData()
      return Promise.all([v1, v2])
    },
    initData() {
      if (this.operation === 'add') this.initSaveData()
      if (['update', 'view'].indexOf(this.operation) !== -1) this.initUpdateData()
      if (this.operation === 'copyadd') {
        this.initUpdateData().then(_ => {
          this.getBillCode()
          const date = moment().format('YYYY-MM-DD HH:mm:ss')
          this.$set(this.dataObj, 'businessTime', date)
        })
      }
    },
    /**
     * 保存采购订单
     */
    saveData(params) {
      return new Promise((resolve, reject) => {
        addReturnPurchase(params).then(res => {
          resolve(res)
          if (res.data.flag) return this.$notify.success({ title: '保存成功！' })
          this.$notify.error({ title: '保存失败！', message: res.data.message || '' })
        }).catch(err => {
          this.$notify.error({ title: '保存异常！', message: err || '' })
          reject(err)
        })
      })
    },
    /**
     * 重置数据
     */
    resetData() {
      this.initSaveData()
    },
    // on
    onTdMouseEnter(e) {
      const target = e.target
      target.className = 'bg-gay'
    },
    onTdMouseLeave(e) {
      const target = e.target
      target.className = ''
    },
    onComegoChange(data) {
      const { id, name } = data
      this.$set(this.dataObj, 'comegoId', id)
      this.$set(this.dataObj, 'comegoName', name)
    },
    onSelectGoodsSure(data) {
      this.$refs.GoodsSelect.pushTableData(data)
    }
  }
}
</script>
